package org.jflame.context.spring.jackson;

import org.jflame.commons.util.DateHelper;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

import org.springframework.context.i18n.LocaleContextHolder;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;

/**
 * 带上下文时区的JsonSerializer. 当配置的全局时区与上下文带的时区不同时,转为该时区时间再格式化.
 * 
 * @author charles.zhang
 */
public class LocalDateTimeWithContextZoneSerializer extends LocalDateTimeSerializer {

    private static final long serialVersionUID = 2503983471179058422L;

    public LocalDateTimeWithContextZoneSerializer() {
        super(DateHelper.FORMATTER_YYYY_MM_DD_HH_mm_ss);
    }

    public LocalDateTimeWithContextZoneSerializer(DateTimeFormatter f) {
        super(f);
    }

    @Override
    public void serialize(LocalDateTime value, JsonGenerator g, SerializerProvider provider) throws IOException {
        TimeZone contextZone = LocaleContextHolder.getTimeZone();
        TimeZone jacksonZone = provider.getTimeZone();

        if (contextZone != null && contextZone.getRawOffset() != jacksonZone.getRawOffset()) {
            LocalDateTime newVal = DateHelper.changeZone(value, jacksonZone, contextZone);
            super.serialize(newVal, g, provider);
        } else {
            super.serialize(value, g, provider);
        }
    }

    @Override
    public void serializeWithType(LocalDateTime value, JsonGenerator g, SerializerProvider provider,
            TypeSerializer typeSer) throws IOException {
        TimeZone contextZone = LocaleContextHolder.getTimeZone();
        TimeZone jacksonZone = provider.getTimeZone();
        if (contextZone != null && contextZone.getRawOffset() != jacksonZone.getRawOffset()) {
            LocalDateTime newVal = DateHelper.changeZone(value, jacksonZone, contextZone);
            super.serializeWithType(newVal, g, provider, typeSer);
        } else {
            super.serializeWithType(value, g, provider, typeSer);
        }
    }

    /*private void format(LocalDateTime value, JsonGenerator g, ZoneId jacksonZone, ZoneId contextZoneId)
            throws IOException {
        LocalDateTime newVal = DateHelper.changeZone(value, jacksonZone, contextZoneId);
        DateTimeFormatter dtf = _formatter;
        if (dtf == null) {
            dtf = _defaultFormatter();
        }
        g.writeString(newVal.format(dtf.withZone(contextZoneId)));
    }*/
}
